import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { tap, map } from 'rxjs/operators';
import { STComponent, STColumn, STData } from '@delon/abc';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'test-table-list',
  templateUrl: './test-table-list.component.html',
})
export class TestTableListComponent implements OnInit {
  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false },
  ];
  @ViewChild('st')
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '规则编号', index: 'no' },
    { title: '描述', index: 'description' },
    {
      title: '服务调用次数',
      index: 'callNo',
      type: 'number',
      format: (item: any) => `${item.callNo} 万`,
      sorter: (a: any, b: any) => a.callNo - b.callNo,
    },
    {
      title: '状态',
      index: 'status',
      render: 'status',
      filter: {
        menus: this.status,
        fn: (filter: any, record: any) => record.status === filter.index,
      },
    },
    {
      title: '更新时间',
      index: 'updatedAt',
      type: 'date',
      sort: {
        compare: (a: any, b: any) => a.updatedAt - b.updatedAt,
      },
    },
    {
      title: '操作',
      buttons: [
        {
          text: '详情',
          click: (item: any) => this.detail(item),
        },
        {
          text: '修改',
          click: (item: any) => this.update(item),
        },
        {
          text: '删除',
          click: (item: any) => this.delete(item),
        },
      ],
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private router: Router,
  ) {}

  ngOnInit() {
    this.getData();
    this.getNewData();
  }

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);
    if (this.q.status !== null && this.q.status > -1){
      this.q.statusList.push(this.q.status);
    }
    const params = {
      'body': {
          'pageInfo': {
              'page': this.q.pi,
              'pageSize': this.q.ps
          },
          'ruleDTO': {

          }
      }
    };
    this.http
      // .post<any>('http://127.0.0.1:9080/api/angular/angular/getTestTablePageList', params)
      .post<any>('/api/angular/angular/getTestTablePageList', params)
      .pipe(
        // map((response: any) =>
        //   response.body.ruleDTOList.map(i => {
        //     const statusItem = this.status[i.status];
        //     i.statusText = statusItem.text;
        //     i.statusType = statusItem.type;
        //     return i;
        //   }),
        // ),
        tap(() => (this.loading = false)),
      )
      .subscribe(response => (this.data = response.body.ruleDTOList,console.log(response.body.ruleDTOList)));
  }

  getNewData() {
    const heroesUrl: string = '/api/angular/angular/getAngularList';
    // const heroesUrl: string = 'http://127.0.0.1:9080/api/angular/angular/getAngularList';
    this.http
      .get(heroesUrl)
      .pipe(
        tap(() => (this.loading = false)),
      )
      .subscribe(res => (console.log(res)));

    this.http
      .post<any>('/api/angular/appInfo/demo', {})
      .pipe(
        tap(() => (this.loading = false)),
      )
      .subscribe(response => {const appInfo = response.body.appInfoDTO; console.log(appInfo.id)});
  }

  checkboxChange(list: STData[]) {
    this.selectedRows = list;
    this.totalCallNo = this.selectedRows.reduce(
      (total, cv) => total + cv.callNo,
      0,
    );
  }

  remove() {
    this.http
      .delete('/rule', { nos: this.selectedRows.map(i => i.no).join(',') })
      .subscribe(() => {
        this.getData();
        this.st.clearCheck();
      });
  }

  approval() {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  add(tpl: TemplateRef<{}>) {

    this.router.navigate(['/pro/list/test-rule-add']);
    // this.modalSrv.create({
    //   nzTitle: '新建规则',
    //   nzContent: tpl,
    //   nzOnOk: () => {
    //     this.loading = true;
    //     this.http
    //       .post('/rule', { description: this.description })
    //       .subscribe(() => {
    //         this.getData();
    //       });
    //   },
    // });
  }

  detail(item: any){
    console.log("detail"+item.key);
    this.router.navigate(['/pro/list/test-rule-detail',{id: item.key, type: false}]);
  }

  update(item: any){
    console.log("update"+item.key);
    this.router.navigate(['/pro/list/test-rule-detail',{id: item.key, type: true}]);
  }

  delete(item: any){
    console.log("delete"+item.key)
    const params = {
      'body': {
          'repositoryDTO': {

          }
      }
    };
    this.http
      .post<any>('http://127.0.0.1:9080/api/angular/angular/deleteRepository', params)
      .pipe(
        tap(() => (this.loading = false)),
      )
      .subscribe(response => (this.data = response.body.ruleDTOList,console.log(response.body.ruleDTOList)));
  }

  reset(ls: any[]) {
    for (const item of ls) item.value = false;
    this.getData();
  }
}
